import camelCase from 'camelcase';
import _ from 'lodash';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { View, StyleSheet, TouchableOpacity, TouchableHighlight, Text, FlatList, Image } from 'react-native';
import { Popup, Utils, Notification } from 'tuya-panel-kit';
import TYSdk from '../../api';
import GridLayout from '../../components/GridLayout';
import dpCodes from '../../config/dpCodes';
import Strings from '../../i18n';
import icons from '../../res/iconfont.json';
import Res from '../../res';
import { store } from '../../redux/configureStore';
import { debounce } from '../../utils';
import { responseUpdateDp } from '../../redux/modules/common';

const { isIphoneX, convertX: cx, convertY: cy, viewWidth } = Utils.RatioUtils;

const TYDevice = TYSdk.device;
const TYNative = TYSdk.native;

const {
  trigger_status: trigger_statusCode,
  no_reminder_status: no_reminder_statusCode,
} = dpCodes;

class HomeErrortipsView extends Component {

  static defaultProps = {
    dpState: {},
    trigger_status: 0,
    no_reminder_status: 0,
  };

  constructor(props) {
    super(props);

    this.state = {
      showErrorArray: [],
    };
  }

  componentDidMount() {

    // 写在这里拿不到实时数据
    // const { trigger_status, no_reminder_status } = this.props;
    // console.log('异常 trigger_status', trigger_status);
    // const binaryArray = decimalToBinaryArray(trigger_status);
    // const noReminder = decimalToBinaryArray(no_reminder_status);
    // const showErrorArray = showErrorBinaryArray(binaryArray, noReminder);
    //
    // this.setState({ showErrorArray });
  }


  closeClick = debounce((v) => {
    const { no_reminder_status } = this.props;
    let noRemider = no_reminder_status + v;
    TYDevice.putDeviceData({
      [no_reminder_statusCode]: noRemider,
    });
  });

  tipsview(item, index) {
    return (
      <TouchableHighlight
        style={styles.cell}
        activeOpacity={0.5}
        underlayColor="#DDDDDD"
        onPress={() => {
          TYSdk.Navigator.push({
            id: 'errorList',
            errorValue: errorValue[index],
          });
        }}
      >
        <View style={styles.bgView} >
          <View style={styles.tips}>
            <Image style={styles.icon} resizeMode="center" source={Res.fwarn} />
            <View style={styles.cellBgView}>
              <Text style={[styles.cellTitle, { paddingTop: 10}]}>{errorList[index]}</Text>
              <Text numberOfLines={2} style={[styles.cellTitle, { fontWeight: 'normal', fontSize: 13, marginTop: 5, paddingBottom: 10 }]}>
                {errorTips[index]}
              </Text>
            </View>
          </View>

          <TouchableOpacity
            style={styles.close}
            onPress={() => {
              this.closeClick(errorValue[index]);
            }}
          >
            <View style={styles.close}>
              <Image style={styles.closeIcon} source={Res.fclose} resizeMode="center" />
            </View>
          </TouchableOpacity>
        </View>

      </TouchableHighlight>
    );
  }

  render() {

    const { trigger_status, no_reminder_status } = this.props;
    // console.log('异常 trigger_status', trigger_status, 'no_reminder_status', no_reminder_status);

    const binaryArray = decimalToBinaryArray(trigger_status);
    const noReminder = decimalToBinaryArray(no_reminder_status);
    const showErrorArray = showErrorBinaryArray(binaryArray, noReminder);

    // this.setState({ showErrorArray });

    // const { showErrorArray } = this.state;
    // const error = ['0', '0', '0', '1', 0, 0, 0, 0, 0, 0]; // 需要传这个异常参数
    // const value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512];
    const renderItem = ({ item, index }) => (item === '1' ? this.tipsview(item, index) : null);

    return (
      <View style={[styles.container]}>
        {/*  */}
        <FlatList
          data={showErrorArray}
          renderItem={renderItem}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}

function decimalToBinaryArray(decimalNumber) {
  // 使用.toString(2)将十进制转换为二进制字符串
  const binaryString = decimalNumber.toString(2);
  // console.log(binaryString);

  // 字符串前面补0，10是目标长度
  const padStringWithZeroes = binaryString.padStart(10, '0');
  // console.log(padStringWithZeroes);

  // 字符串反转
  let reverseString = padStringWithZeroes.split('').reverse().join('');
  // console.log(reverseString);

  // 字符串截取
  if (reverseString.length > 10) {
    reverseString = reverseString.slice(0, 10);
  }

  // 将二进制字符串转换为数组
  return reverseString.split('');
}

function showErrorBinaryArray(errorArray, noReminderArray) {

  // console.log('异常状态', errorArray);
  let showError = [];
  errorArray.forEach((item, index) => {
    let error = item;
    for (let i = 0; i < noReminderArray.length; i++) {
      const item2 = noReminderArray[i];
      if (index === i){
        if (item === '1' && item2 === '1') {
          item = '0';
          error = '0';
        }
      }
    }
    showError.push(error);
  })

  return showError;
}

// 按照bit，从低到高位。1，水草灯时间过长。2，水泵故障。3，水泵低水位。4，水泵堵转。5，水泵未连接。
// 6，今日喂食份数过多。7，水温提醒。8，物理滤材过期。9，生化滤材过期。10，水泵过滤棉清洗提醒（运行时间超过阈值）
const errorList = [
  Strings.warning_card_title_water_grass_too_long,//'水草灯时间过长',
  Strings.warning_card_title_pump_fault,//'水泵故障',
  Strings.warning_card_title_pump_low,//'水泵低水位',
  Strings.warning_card_title_pump_blocked,//'水泵堵转',
  Strings.warning_card_title_pump_disconnected,//'水泵未连接',
  Strings.warning_card_title_feed_too_many,//'今日喂食份数过多',
  Strings.warning_card_title_temp_warning,//'水温提醒',
  Strings.warning_card_title_filter_wuli_expired,//'物理滤材过期',
  Strings.warning_card_title_filter_shenghua_expired,//'生化滤材过期',
  Strings.warning_card_title_pump_filter_cotton,//'水泵过滤棉清洗提醒',
];

const errorTips = [
  Strings.warning_card_desc_water_grass_too_long,//'请立即关闭水草灯，以防鱼缸爆藻',
  Strings.warning_card_desc_pump_fault,//'点击查看水泵故障排查的详细步骤',
  Strings.warning_card_desc_pump_low,//'请将水加至鱼缸的Min线以上',
  Strings.warning_card_desc_pump_blocked,//'点击查看清洗水泵的详细步骤',
  Strings.warning_card_desc_pump_disconnected,//'点击查看连接水泵的详细步骤',
  Strings.warning_card_desc_feed_too_many,//'请注意喂食频次',
  Strings.warning_card_desc_temp_warning,//'请注意控制水温，当前已超过指定温度范围',
  Strings.warning_card_desc_filter_expired,//'请及时更换滤材已保持过滤系统正常运行',
  Strings.warning_card_desc_filter_expired,//'请及时更换滤材已保持过滤系统正常运行',
  Strings.warning_card_desc_pump_filter_cotton,//'请每月清洗水泵仓过滤棉，避免滤棉堵塞，造成水泵异响、堵转等问题',
];

const errorValue = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512];

const styles = StyleSheet.create({
  container: {
    alignSelf: 'stretch',
    marginTop: -50,
  },
  tips: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    flex: 1,
    alignItems: 'center',// 水平居中子元素
  },
  cell: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#fff',
    // height: 80,
    marginStart: 10,
    marginEnd: 10,
    marginTop: 10,
    // width: '100%',
    borderRadius: 12,
  },
  cellBgView: {
    marginStart: 10,
  },
  bgView:{
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#ffffff',
    borderRadius: 12,
  },
  cellTitle: {
    marginStart: 10,
    fontSize: 16,
    fontWeight: 'bold',
    color: '#000',
    width: 200,
    // backgroundColor: '#b4dcec',
  },
  icon: {
    justifyContent: 'center',
    marginStart: 30,
    width: 40,
    height: 40,
  },
  close: {
    justifyContent: 'center',
    marginRight: 0,
    width: 80,
    height: 80,
    // backgroundColor: '#22a8dc',
  },
  closeIcon: {
    justifyContent: 'center',
    marginRight: 0,
    width: 80,
    height: 80,
  },
});

export default connect(({ dpState }) => ({
  dpState,
  trigger_status: dpState[trigger_statusCode],
  no_reminder_status: dpState[no_reminder_statusCode],
}))(HomeErrortipsView);
